//
//  LZOauthController.swift
//  Weibo
//
//  Created by lzing on 16/3/21.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit
import SVProgressHUD

class LZOauthController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置背景色,加载导航条按钮
        view.backgroundColor = UIColor.whiteColor()
        loadNavigationBar()
        /// 加载url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let urlRequest = NSURLRequest(URL: url!)
        webView.loadRequest(urlRequest)
        // 显示遮盖
        SVProgressHUD.showWithStatus("正在加载中", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    /// 加载导航条
    private func loadNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fullBtnDidClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnDidClick")
    }
    
    /**
    填充按钮点击
     */
    @objc private func fullBtnDidClick() {
        
        let script = "document.getElementById('userId').value='13510293362';document.getElementById('passwd').value='bybiiihappy0'"
        webView.stringByEvaluatingJavaScriptFromString(script)
    }
    
    /**
     取消按钮点击事件
     */
    @objc private func cancelBtnDidClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - lazy
    private lazy var webView : UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
}

// MARK - webView代理方法
extension LZOauthController : UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 路径
        let urlString = request.URL!.absoluteString
        
        // 如果不是授权地址就让他加载
        if !urlString.hasPrefix(redirect_uri) {
           return true
        } else {
            // 获取query:?后面的参数
            let query = request.URL?.query
            // 判断是否以code=开头
            let codeStr = "code="
            if query!.hasPrefix(codeStr) {
                // 截取code
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeStr.characters.count)
                // 准备闭包
                LZUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil {
                        // 请求失败
                        SVProgressHUD.showErrorWithStatus("请求accessToken失败", maskType: SVProgressHUDMaskType.Gradient)
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.cancelBtnDidClick()
                        })
                        return
                    }
                    // 跳转控制器
                    AppDelegate.outSwitchRootViewController(LZWelcomeController())
                })
                // 关闭视图
                cancelBtnDidClick()
                
            } else {
                // 关闭视图
                cancelBtnDidClick()
            }
        }
        return false
    }
}
